package edu.nepu.flink.introduction;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


/**
 * time： 2024年1月22日16:11:39
 * user: chenshuaijun
 * 备注：真是汗颜啊，一个简单的wordCount写了半天，真的是太长时间没有写代码了，基本的api就已经忘了
 */
public class WordCount {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // 从socket中读取数据
        DataStreamSource<String> socketStream = env.socketTextStream("hadoop102", 9999);
        // 将数据进行切分
        SingleOutputStreamOperator<String> flatmapStream = socketStream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(word);
                }
            }
        });
        // 转换数据结构，将数据从word变成[word,1]方便后面的聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapStream = flatmapStream.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return Tuple2.of(s,1);
            }
        });
        // 对数据进行分组
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = mapStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> stringIntegerTuple2) throws Exception {
                return stringIntegerTuple2.f0;
            }
        });
        // sum中指定我们以value中哪一个字段（名字/位置）进行聚合
        keyedStream.sum(1).print();

        env.execute();


    }
}
